import {
  ValidatorConstraint,
  ValidatorConstraintInterface,
  registerDecorator,
  ValidationOptions,
  ValidationArguments,
  isString,
} from 'class-validator';

@ValidatorConstraint({ name: 'IsStringRw', async: false })
export class MyIsString implements ValidatorConstraintInterface {
  validate(value: string, args: ValidationArguments) {
    // 继承
    if (!isString(value)) {
      return false;
    }

    // 添加额外逻辑
    return true;
  }

  defaultMessage(args: ValidationArguments) {
    return `${args.property} 必须是一个字符串`;
  }
}

export function IsStringRw(validationOptions?: ValidationOptions) {
  return function (object: object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: MyIsString,
    });
  };
}
